<template>
  <div>
    <!--  面包屑-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  卡片  -->
    <el-card>
      <el-alert show-icon title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false">
      </el-alert>
      <el-row>
        <el-col><span>选择商品分类：</span>
          <!--          级联选择器-->
          <el-cascader v-model="selectKeys" :options="catelist"
                       :props="propsCate" @change="changeCate"></el-cascader>
        </el-col>
      </el-row>
      <!--    标签页-->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!--        动态参数-->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="small" :disabled="isBtnShow" @click="addDialogVisible = true">添加参数</el-button>
          <!--          表格-->
          <el-table :data="manyTable" style="width: 100%" border stripe>
            <el-table-column type="expand">
              <template #default="scope">
                <el-tag closable @close="deleteTag(i,scope.row)" v-for="(item,i) in scope.row.attr_vals" :key="i">{{ item }}</el-tag>
                <el-input
                  class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editEditShow (scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="editFormDeleted(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!--        静态属性-->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="small" :disabled="isBtnShow" @click="addDialogVisible = true">添加参数</el-button>
          <!--          表格-->
          <el-table :data="onlyTable" style="width: 100%" border stripe>
            <el-table-column type="expand">
              <template #default="scope">
                <el-tag closable @close="deleteTag(i,scope.row)" v-for="(item,i) in scope.row.attr_vals" :key="i">{{ item }}</el-tag>
                <el-input
                  class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editEditShow(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="editFormDeleted(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
<!--    添加参数的对话框（动态静态合并写）-->
    <el-dialog :title="'添加' + titleText" :visible.sync="addDialogVisible" width="40%" @close="addFormClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAddForm">确 定</el-button>
      </span>
    </el-dialog>
    <!--    编辑按钮的对话框-->
    <el-dialog :title="'修改' + titleText" :visible.sync="editDialogVisible" width="40%" @close="editFormClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data () {
    return {
      // 商品分类数据,在级联选择器列表显示
      catelist: [],
      // 级联选择器属性的设定
      propsCate: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择器选中的值
      selectKeys: [],
      // 标签页的数据对象
      activeName: 'many',
      // 动态参数的表格
      manyTable: [],
      // 静态参数的表格
      onlyTable: [],
      // 添加参数的对话框显示
      addDialogVisible: false,
      // 添加参数表单
      addForm: {},
      // 添加表单的规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 修改对话框的表单显示
      editDialogVisible: false,
      // 修改表单
      editForm: {
      },
      // 修改表单的规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取分类的列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取分类数据失败')
      this.catelist = res.data
      // console.log(this.catelist)
    },
    // 级联选择器里的值改变的时候，只给他选第三级分类
    async changeCate () {
      this.getParamsData()
    },
    // 改变标签页触发的事件
    handleTabClick () {
      console.log(this.activeName)
      this.getParamsData()
    },
    async getParamsData () {
      // console.log(this.selectKeys)
      if (this.selectKeys.length !== 3) {
        this.selectKeys = []
        this.manyTable = []
        this.onlyTable = []
        return false
      }
      const { data: res } = await this.$http.get('categories/' + this.selectCateId + '/attributes',
        { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('参数列表获取失败')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 动态标签的切换显示属性
        item.inputVisible = false
        // 动态标签的输入的双向数据绑定
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTable = res.data
      } else {
        this.onlyTable = res.data
      }
      // console.log(res.data[0].attr_vals)
      console.log(res)
    },
    // 添加参数对话框，点击确定按钮触发保存事件
    saveAddForm () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post('categories/' + this.selectCateId + '/attributes',
          { attr_name: this.addForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.$message.success('添加成功')
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    // 重置添加对话框
    addFormClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 点击编辑按钮触发的事件，显示修改表单
    editEditShow (row) {
      console.log(row)
      this.editForm = { ...row }
      this.editDialogVisible = true
    },
    // 关闭修改表单触发的事件
    editFormClosed () {
      this.editForm.attr_name = ''
      this.$refs.editFormRef.resetFields()
    },
    // 点击修改对话框，保存修改的值
    saveEditForm () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return false
        // console.log(this.editForm)
        const { data: res } = await this.$http.put('categories/' + this.editForm.cat_id + '/attributes/' + this.editForm.attr_id,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('提交参数失败')
        this.$message.success('提交成功')
        this.getParamsData()
        this.editDialogVisible = false
      })
    },
    // 删除数据
    async editFormDeleted (id) {
      console.log(id)
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirmResult)
      if (confirmResult !== 'confirm') return this.$message.info('取消删除')
      const { data: res } = await this.$http.delete('categories/' + this.selectCateId + '/attributes/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getParamsData()
    },
    // 动态标签是输入框时候触发的事件
    handleInputConfirm (row) {
      // 输入不合法时
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return false
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveTagInfo(row)
    },
    // 将标签信息保存到数据库
    async saveTagInfo (row) {
      const { data: res } = await this.$http.put('categories/' + this.selectCateId + '/attributes/' + row.attr_id,
        { attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(' ') })
      if (res.meta.status !== 200) return this.$message.info('添加标签失败')
      this.$message.success('修改成功')
    },
    // 动态标签是Button时候的触发事件
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 标签的删除操作
    deleteTag (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveTagInfo(row)
    }
  },
  computed: {
    isBtnShow () {
      if (this.selectKeys.length !== 3) return true
      return false
    },
    selectCateId () {
      if (this.selectKeys.length === 3) { return this.selectKeys[2] }
      return null
    },
    titleText () {
      if (this.activeName === 'many') { return '动态参数' } else return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.el-alert{
  margin-bottom: 15px;
}
.el-tabs{
  margin-top: 10px;
}
.input-new-tag{
  width: 120px;
}
.el-tag{
  margin: 0 10px;
}
</style>
